package im430.santashelper.springmvc;

import im430.santashelper.business.Gift;
import im430.santashelper.dao.ChildDAO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/gifts")
public class GiftsController {

	private ChildDAO childDAO;
	
	@RequestMapping(value = "/create/{childId}", method = RequestMethod.GET)
	public String formCreateGift(@PathVariable int childId, @ModelAttribute Gift gift, Model model) {
		model.addAttribute("child", getChildDAO().getChildById(childId));
		gift = new Gift();
		return "gifts/create";
	}
	
	@RequestMapping(value = "/create/{childId}", method = RequestMethod.POST)
	public String createGift(@PathVariable int childId, Gift gift) {
		getChildDAO().addGift(getChildDAO().getChildById(childId), gift);
		return "redirect:../../children/read/" + childId;
	}

	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String formUpdateGift(@PathVariable int id, @ModelAttribute Gift gift, Model model) {
		gift = getChildDAO().getGiftById(id);
		model.addAttribute("giftData", gift);
		model.addAttribute("child_id", getChildDAO().getChildIdFromGift(gift));
		return "gifts/update";
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String updateGift(Gift gift) {
		getChildDAO().updateGift(gift);
		return "redirect:../../children/read/" + getChildDAO().getChildIdFromGift(gift);
	}
	
	@RequestMapping(value = "/delete/{giftId}", method = RequestMethod.GET)
	public String confirmDeleteGift(@PathVariable int giftId, Model model) {
		Gift g = getChildDAO().getGiftById(giftId);
		model.addAttribute("gift", g);
		model.addAttribute("child_id", getChildDAO().getChildIdFromGift(g));
		return "gifts/delete";
	}

	@RequestMapping(value = "/delete/{giftId}", method = RequestMethod.POST)
	public String deleteGift(@PathVariable int giftId) {
		Gift g = getChildDAO().getGiftById(giftId);
		int childId = getChildDAO().getChildIdFromGift(g);
		getChildDAO().removeGift(g);
		return "redirect:../../children/read/" + childId;
	}

	public ChildDAO getChildDAO() {
		return childDAO;
	}

	@Autowired
	public void setChildDAO(ChildDAO childDAO) {
		this.childDAO = childDAO;
	}

}